<?php
class PostsController extends CController {
	public $currentCategoryId;

	public function actions() {
		return array(
			// Captcha action renders the CAPTCHA image
			'captcha' => array(
				'class' => 'CCaptchaAction',
				'backColor' => 0xF5F5F5,
				'foreColor' => 0x6C8D00,
				'maxLength' => 5,
				'minLength' => 5,
				'padding' => 2,
				'height' => 30,
				'width' => 80
			)
		);
	}

    public function beforeAction($action) {
        if(Yii::app()->getUrlManager()->getUrlFormat() == 'get') {
            Yii::app()->getUrlManager()->setUrlFormat('path');
        }
        return true;
    }
	
	public function actionView() {
		$post = $this->loadPost();
		$post->postRead = $post->postRead+1;
		$post->save();
		$with = array('author');
		$comments = Comments::model()->with($with)->findAllByAttributes(array('postId' => $post->postId), array('order' => 'commentId ASC'));
		$commentsCount = count($comments);
		$_comment = new Comments;

		if($post->metaKey != '') {
			Yii::app()->clientScript->registerMetaTag(htmlspecialchars($post->metaKey), 'keywords');
		}
		if($post->metaDescr != '') {
			Yii::app()->clientScript->registerMetaTag(htmlspecialchars($post->metaDescr), 'description');
		}

		// The previous one and the next one
		$criteria = new CDbCriteria;
		$criteria->addCondition('postId > '.$post->postId);
		$criteria->order = 'postId';
		$criteria->limit = 1;
		$nextPost = Posts::model()->published()->find($criteria);
		$criteria = new CDbCriteria;
		$criteria->addCondition('postId < '.$post->postId);
		$criteria->order = 'postId DESC';
		$criteria->limit = 1;
		$prevPost = Posts::model()->published()->find($criteria);
		
		// Render to view
		Yii::app()->layout = 'layoutsLite';
		Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/js/postView.js', CClientScript::POS_END);
		$this->setPageTitle($post->postTitle.'  _'.$post->categories[0]->terms->name.' - 广州心理咨询网');
		$this->render('postView', array(
				'post' => $post,
				'comments' => $comments,
				'commentsCount' => $commentsCount,
				'category' => $post->categories[0]->terms,
				'_comment' => $_comment,
				'nextPost' => $nextPost,
				'prevPost' => $prevPost
			)
		);
	}

	public function actionListByTopic() {
		$topicId = isset($_GET['id']) ? (int)$_GET['id'] : null;

		if($topicId !== null) {
			$criteria = new CDbCriteria;
			$criteria->condition = 'termTaxonomyId = '.$topicId;
			$topic = TermsTaxonomy::model()->topic()->find($criteria);
			if($topic !== null) {
				$criteria = new CDbCriteria;
				$criteria->order = 'postId DESC';
				$criteria->condition = 'termTaxonomyId = '.$topicId;
				$with = array('topics');
				// Get the count of all posts
				$postsCount = Posts::model()->published()->with($with)->count($criteria);
				// Pagination
				$pages = new CPagination($postsCount);
				$pages->pageSize = 10;
				$pages->applyLimit($criteria);
				$posts = Posts::model()->published()->findByTopicId($topicId, $criteria);
	
				$this->setPageTitle($topic->terms->name.'的文章 - 广州心理咨询网');
				$this->render('list_by_topic', array(
						'posts' => $posts,
						'pages' => $pages,
						'topic' => $topic
					)
				);
			}
		}
	}
	
	public function actionPostComment() {
		if(isPost()) {
			$comment = new Comments;
			$comment->attributes = $_POST['Comments'];
			$comment->verifyCode = $_POST['Comments']['verifyCode'];
			$comment->userId = Users::isLogin();
			$comment->commentDate = time();
			$comment->commentIp = $_SERVER['REMOTE_ADDR'];
			$comment->postId = $_POST['Posts']['postId'];
			if( ! $comment->save()) {
				Yii::app()->user->setFlash('errors', $comment->getErrors());
				Yii::app()->user->setFlash('comment', $comment);
				$this->redirect(array('posts/view', 'id' => $comment->postId, '#' => 'postComment'));
			} else {
				$this->redirect(array('posts/view', 'id' => $comment->postId, '#' => 'commentsList'));
			}
		}
	}
	
	public function actionCategory() {
		$categoryId = isset($_GET['id']) ? (int)$_GET['id'] : null;

        if($categoryId === null && isset($_GET['name'])) {
    		switch($_GET['name']) {
    			case '咨询专题':
    				$categoryId = 32;
    				break;
    			case '心理文丛':
    				$categoryId = 1;
    				break;
    			case '心理学堂':
    				$categoryId = 8;
    				break;
    			case '企业EAP':
    				$categoryId = 11;
    				break;
    			case '咨询案例':
    				$categoryId = 43;
    				break;
    		}
        }

        $category = TermsTaxonomy::model()->with('terms')->find('termTaxonomyId = ? AND taxonomy = ?', array(
            $categoryId,
            TermsTaxonomy::TAXONOMY_CATEGORY
        ));
		$this->currentCategoryId = $categoryId;

		$posts = array();
		foreach($category->getChildren() as $k => $subCategory) {
			$posts[$k]['meta'] = TermsTaxonomy::model()->findByPk($subCategory->termTaxonomyId);
			$posts[$k]['rows'] = Posts::model()->published()->section()->findByCategoryId($subCategory->termTaxonomyId);
		}

		$this->setPageTitle($category->terms->name.' - 广州心理咨询网');
		$this->render('list', array(
				'posts' => $posts,
                'category' => $category,
				'categoryName' => $category->terms->name
			)
		);
	}
	
	public function actionSearch() {
		if(isset($_GET['key'])) {
			$key = trim(urldecode($_GET['key']));
			$errors = array();
			if(strlen($key) <= 3) {
				$errors[] = '您输入的搜索关键字过短，请重新输入。';
			}
			if( ! sizeof($errors) > 0) {
				$criteria = new CDbCriteria;
				$criteria->order = 'postId DESC';
				$criteria->addSearchCondition('postTitle', $key, true, 'OR')
					->addSearchCondition('postContent', $key, true, 'OR');
				$with = array('categories');
				// Get the count of all posts
				$postsCount = Posts::model()->published()->with($with)->count($criteria);
				// Pagination
				$pages = new CPagination($postsCount);
				$pages->pageSize = 10;
				$pages->params = array('key' => urlencode($key));
				$pages->applyLimit($criteria);
				// Posts' data
				$posts = Posts::model()->published()->with($with)->findAll($criteria);
			}
			$this->setPageTitle('广州心理咨询网 - 搜索结果“'.$key.'”');
			$this->render('search', array(
					'posts' => isset($posts) ? $posts : null,
					'pages' => isset($pages) ? $pages : new CPagination,
					'key' => (htmlspecialchars($key)),
					'errors' => $errors
				)
			);
		}
	}
	
	protected function loadPost($id = null, $slug = null) {
		if($id !== null || isset($_GET['id'])) {
			$post = Posts::model()->with('categories')->findByPk($id !== null ? $id : (int)$_GET['id']);
            if($post !== null) {
                $this->redirect($post->getRewrittenUrl(), 301);
            }
		} else if($slug !== null || isset($_GET['slug'])) {
			$post = Posts::model()->findBySlug($slug !== null ? $slug : (string)trim($_GET['slug'], '/'));
		}

		if($post === null || ($post->postStatus != Posts::STATUS_PUBLISHED && ! ForumMembers::isAdmin())) {
			throw new CHttpException(404, 'The requested post does not exist.');
		}
		return $post;
	}
}
